//
//  SendBlogVC.swift
//  我的微博
//
//  Created by shmily on 15/8/5.
//  Copyright © 2015年 Stanford-IOS8-Swift-shmilyAshen. All rights reserved.
//

import UIKit
import SVProgressHUD

/// 发送微博的控制器
class SendBlogVC: UIViewController {
    /// 工具栏的 底部 约束
    var toobarCons: NSLayoutConstraint?
    /// 允许输入最大的文本长度
    private let KMaxLength = 10
    
    /// 发送微博
    func barBtnSend() {
        let image: UIImage? = (picturePick.images.count > 0) ? picturePick.images[0] : nil
        
        NetworkingTools.sharedNetTool.sendBlog(textView.text, image: image) { (result, error) -> () in
            if error != nil {
                print(error)
                SVProgressHUD.showInfoWithStatus("出错了")
            }
            SVProgressHUD.showInfoWithStatus("发送成功")
            self.dismissViewControllerAnimated(true, completion: nil) // 关闭发送按钮
        }
    }
    /// 取消发送微博
    func barBtnCancel() {
        //关闭键盘
        view.endEditing(true)
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 显示表情按钮
    func inputEmoticon() {
        resignNotification() //关闭通知
        textView.resignFirstResponder()
        
        emoticonVC.textView = textView
        textView.inputView = (textView.inputView == nil) ? emoticonVC.view : nil
        
        addNotification() //打开通知
        textView.becomeFirstResponder()
    }
    
    /// 显示图片选择器
    func picturePickClick() {
    
    }
    
    /// 添加键盘通知
    private func addNotification() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "moveToolBar:", name:UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    /// 关闭键盘通知
    private func resignNotification() {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    /// toolBar 跟随键盘移动
    func moveToolBar(info: NSNotification) {
        let duration = info.userInfo![UIKeyboardAnimationDurationUserInfoKey]?.doubleValue
        let rect = info.userInfo![UIKeyboardFrameEndUserInfoKey]?.CGRectValue
        
        toobarCons?.constant = rect!.origin.y - UIScreen.mainScreen().bounds.height
        UIView.animateWithDuration(duration!) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    //MARK:- 视图相关
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        
        setupUI()
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        //添加键盘通知
        addNotification()
        lblLast.text = String(KMaxLength)
    }

    //设置视图
    private func setupUI() {
        view.backgroundColor = UIColor.whiteColor()
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "barBtnCancel")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "barBtnSend")
        //设置为不可用状态
        navigationItem.rightBarButtonItem?.enabled = false
        
        view.addSubview(textView)

        //添加图片选择器
        view.addSubview(picturePick.view!)
        picturePick.view!.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: CGSize(width: view.bounds.size.width, height: view.bounds.size.height * 0.6), offset: CGPoint(x: 0, y: 260))
        addChildViewController(picturePick) //TODO:重要
        
        //添加工具栏
        view.addSubview(toolBar)
        let cons = toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view,size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44))
        toobarCons = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        //添加文本框
        textView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil,offset: CGPoint(x: 0, y: 0))
        textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolBar, size: nil)
        textView.delegate = self
        textView.becomeFirstResponder()
        
        //添加 mask 标签
        textView.addSubview(lblMask)
        lblMask.ff_AlignInner(type: ff_AlignType.TopLeft, referView: textView, size: nil, offset: CGPoint(x: 3, y: 6))
        
        //添加剩余文本
        view.addSubview(lblLast)
        lblLast.ff_AlignInner(type: ff_AlignType.BottomRight, referView: textView, size: nil, offset: CGPoint(x: -8, y: -8))
        
        // 添加发送微博提示
        navigationItem.titleView?.addSubview(viewSendBlog)
        let titleLabel = UILabel(fontSize: 15, foreColor:UIColor.darkGrayColor())
        titleLabel.text = "发微博"
        titleLabel.sizeToFit()
        viewSendBlog.addSubview(titleLabel)
        titleLabel.ff_AlignInner(type: ff_AlignType.TopCenter, referView: viewSendBlog, size: nil)
        
        let nameLabel = UILabel(fontSize: 13, foreColor:UIColor.lightGrayColor())
        nameLabel.text = UserInfo.getUserInfo()?.name ?? ""
        nameLabel.sizeToFit()
        viewSendBlog.addSubview(nameLabel)
        nameLabel.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: viewSendBlog, size: nil)
        navigationItem.titleView = viewSendBlog
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK:- 懒加载视图
    //表情键盘
    private lazy var emoticonVC: EmoticonVC = EmoticonVC()
    //图片选择器
    private lazy var picturePick: PicturePickVC = PicturePickVC()
    //文本标签
    private lazy var textView: UITextView = {
        let text = UITextView()
        text.font = UIFont.systemFontOfSize(32)
        //下拉关闭键盘
        text.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        text.alwaysBounceVertical = true
        return text
    }()
    
    /// 工具栏
    private lazy var toolBar: UIToolbar = {
        let toolbar = UIToolbar()
        
        // 定义一个数组
        let itemSettings = [["imageName": "compose_toolbar_picture","action": "picturePickClick"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        var item = [UIBarButtonItem]()
        //填充工具条
        for dict in itemSettings {
            let barBtn = UIBarButtonItem(imgName: dict["imageName"]! , target: self, action: dict["action"])
            item.append(barBtn)
            //添加弹簧
            item.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        item.removeLast()
        toolbar.items = item
        
        toolbar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        return toolbar
    }()
    //mask 标签
    private lazy var lblMask: UILabel = {
        let lbl = UILabel()
        lbl.textColor = UIColor.lightGrayColor()
        lbl.font = UIFont.systemFontOfSize(32)
        lbl.text = "分享新鲜事..."
        lbl.sizeToFit()
        return lbl
    }()
    // 剩余输入文本
    private lazy var lblLast: UILabel = {
        let lbl = UILabel(fontSize: 12, foreColor: UIColor.lightGrayColor())
        lbl.sizeToFit()
        return lbl
    }()
    // 发送微博提示栏
    private lazy var viewSendBlog: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 32))
}
// MARK: - UITextViewDelegate 的代理方法,实现文本改变触发事件
extension SendBlogVC: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        lblMask.hidden = textView.hasText() //隐藏文本
        navigationItem.rightBarButtonItem?.enabled = textView.hasText() //按钮可用
        
        //显示剩余字数
        let text = textView.emoticonText
        let result = KMaxLength - text.characters.count
        lblLast.text = String(result)
        lblLast.textColor = (result > 0) ? UIColor.lightGrayColor() : UIColor.redColor()
        lblLast.sizeToFit()
    }
}

